<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <el-dialog
        title="请选择打印模板"
        :visible.sync="crud.printConfig.pringDialog"
        width="30%"
        v-dialogDrag
      >
        <jPrintConfig groupId="wareAllot"
                      v-if="crud.printConfig.pringDialog"
                      @getPrintId="crud.detailedPrint"
                      :isPreview="crud.printConfig.isPreview"
        ></jPrintConfig>
      </el-dialog>
      <div >
        <el-form size="small" label-width="80px" :rules="rules" ref="form" :model="crud.order"
                 :disabled="crud.order.orderStatus==='PASS'">
          <el-row :gutter="10">
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="单据编码">
                <el-input  v-model="crud.order.code" disabled placeholder="系统自动生成"></el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="状态">
                <el-select
                  v-model="crud.order.orderStatus"
                  class="filter-item"
                  clearable
                  disabled
                  placeholder="状态"
                  size="small"
                  style="width: 100%;"
                >
                  <el-option
                    v-for="item in dict.common_order_status"
                    :key="item.id"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="业务日期">
                <el-date-picker
                  v-model="crud.order.busDate"
                  type="date"
                  style="width: 100%;"
                  format="yyyy - MM - dd "
                  value-format="yyyy-MM-dd"
                  default-value
                  placeholder="选择日期">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="出库仓库" prop="outWarehouseId">
                <zSelect :value.sync="crud.order.outWarehouseId" :showName="crud.order.outWarehouseName" @getChange="getInfoOut" :disabled="crud.order.orderStatus==='PASS'" url="api/dropDown/basWarehouseList"
                         style="width:  100%"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="入库仓库" prop="inWarehouseId">
                <zSelect :value.sync="crud.order.inWarehouseId" :showName="crud.order.inWarehouseName" @getChange="getInfoIn" :disabled="crud.order.orderStatus==='PASS'" url="api/dropDown/basWarehouseList"
                         style="width:  100%"/>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="出库部门" prop="outDeptId">
                <zSelect :value.sync="crud.order.outDeptId"  :showName="crud.order.outDeptName" :disabled="crud.order.orderStatus==='PASS'" url="api/dropDown/childSysDeptList"
                         style="width:  100%"/>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="入库部门" prop="inDeptId">
                <zSelect :value.sync="crud.order.inDeptId" :showName="crud.order.inDeptName" :disabled="crud.order.orderStatus==='PASS'" url="api/dropDown/childSysDeptList"
                         style="width:  100%"/>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="调拨类型">
                <el-select
                  v-model="crud.order.type"
                  class="filter-item"
                  clearable
                  placeholder="调拨类型"
                  size="small"
                  style="width: 100%"
                  @change="crud.toQuery"
                >
                  <el-option
                    v-for="item in dict.t_ware_allot_type"
                    :key="item.id"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10">
<!--            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">-->
<!--              <el-form-item label="供应商" prop="customerId">-->
<!--                <zSelect :value.sync="crud.order.customerId" @getChange="getInfo" :disabled="crud.order.orderStatus==='PASS'" url="api/dropDown/basCustomerList"  :params="{isContact:'1,2'}"-->
<!--                         style="width:  100%"/>-->
<!--              </el-form-item>-->
<!--            </el-col>-->
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="来源类型">
                <el-select v-model="crud.order.sourceType" style="width:  100%"  disabled class="edit-input" placeholder="请选择来源类型" >
                  <el-option
                    v-for="(item,index) in dict.t_ware_allot_source_type"
                    :key="index"
                    v-if="item.seq>0"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="来源单据号">
                <el-input  v-model="crud.order.sourceCode" disabled  placeholder="请输入"></el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="备注">
                <el-input  v-model="crud.order.remark"  :disabled="crud.order.orderStatus==='PASS'"  placeholder="请输入"></el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="单据说明">
                <el-input  v-model="crud.order.orderRemark"  :disabled="crud.order.orderStatus==='PASS'"  placeholder="请输入"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <!--   操作栏   -->
      <crudOperation :permission="permission">
        <el-button
          slot="left"
          class="filter-item"
          size="mini"
          :disabled="crud.order.orderStatus==='PASS'"
          type="primary"
          @click="toAdd()"
        >
          新增
        </el-button>
        <!--        <el-button-->
        <!--          slot="left"-->
        <!--          class="filter-item"-->
        <!--          size="mini"-->
        <!--          type="success"-->
        <!--          :disabled="crud.selections.length !== 1"-->
        <!--          @click="toDeatil(crud.selections)"-->
        <!--        >修改-->
        <!--        </el-button>-->
        <el-button
          slot="right"
          class="filter-item"
          size="mini"
          :disabled="crud.order.orderStatus==='PASS'"
          type="primary"
          @click="submit()"
        >
          保存
        </el-button>

        <el-button
          slot="right"
          class="filter-item"
          size="mini"
          type="success"
          :disabled="crud.order.isPassOut === 1"
          :loading="crud.passLoading"
          @click="handleClickPassOut(id)"

        >
          <!--        v-permission="permission.pass"-->
          审核出库
        </el-button>
        <el-button
          slot="right"
          class="filter-item"
          size="mini"
          type="info"
          :loading="crud.rejectLoading"
          :disabled="crud.order.isPassIn === 1"
          @click="handleClickPassIn(id)"

        >
          <!--        v-permission="permission.reject"-->
          审核入库
        </el-button>
        <el-button
          slot="right"
          class="filter-item"
          size="mini"
          type="info"
          :loading="crud.rejectLoading"
          :disabled="crud.order.isPassOut !== 1"
          @click="handleClickRejectOut(id)"

        >
          <!--        v-permission="permission.reject"-->
          反审出库
        </el-button>
        <el-button
        slot="right"
        class="filter-item"
        size="mini"
        type="info"
        :loading="crud.rejectLoading"
        :disabled="$route.params.id=='add'&&crud.order.orderStatus==='PASS'"
        @click="handleClickReverseAllot(id)"

      >
        <!--        v-permission="permission.reject"-->
        反向调拨
      </el-button>
        <el-button
          slot="right"
          class="filter-item"
          size="mini"
          type="primary"
          @click="toAddList"
        >
          批量新增
        </el-button>
        <el-button
          slot="right"
          :loading="crud.downloadLoading"
          class="filter-item"
          size="mini"
          type="warning"
          @click="crud.preView"
          :disabled="$route.params.id == 'add'"
        >打印</el-button>
        <el-button
          slot="right"
          :loading="crud.downloadLoading"
          class="filter-item"
          size="mini"
          type="warning"
          @click="crud.preView1"
          :disabled="$route.params.id == 'add'"
        >打印预览</el-button>
      </crudOperation>
      <!--      :summary-method="crud.getSummaries"-->
      <el-table ref="table" stripe border  v-loading="crud.loading" :row-class-name="crud.tableRowClassName"
                :data="crud.data"
                height="500"
                size="small" style="width: 100%;"
                :show-summary="true"
                sortable="custom"
                @sort-change="crud.sortChange"
                @selection-change="crud.selectionChangeHandler"
                @row-dblclick="crud.dbClick">
        <el-table-column :render-header="crud.renderHeader" type="selection" width="60" />
        <el-table-column :render-header="crud.renderHeader" type="index" width="60" label="序号"/>
        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('goodsCode')" prop="goodsCode" label="商品编码" />
        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('goodsName')" prop="goodsName" label="商品名称" width="200">
          <template slot-scope="scope">
            <span v-if="!scope.row.isSelected">{{ scope.row.goodsName }}</span>
            <jtg-select-plus v-else ref="productRef"
                             v-model="scope.row.goodsId"
                             :initValue="scope.row.goodsName"
                             :customerId="crud.order.customerId"
                             typeName="STOCK"

                             :buyChannel ="crud.order.buyChannel"
                             @remoteMethod="getValue($event,scope.$index)"
                             @input="getInput($event,name,scope.$index)"
                             @change="crud.productChange($event,scope)"
                             url="productList"/>
          </template>
        </el-table-column>
        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('helpSign')" prop="outUsableBoxNum" label="可用辅数量" >
          <template slot-scope="{row}">
            {{ row.outUsableBoxNum }}{{ row.boxUnitName }}{{ row.outUsableMainNum }}{{ row.mainUnitName }}
          </template>
        </el-table-column>
        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('helpSign')" prop="outUsableNum" label="可用量" />
        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('helpSign')" prop="helpSign" label="助记符" />
        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('model')" prop="model" label="规格型号" />
        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('barcode')" prop="barcode" label="条形码" />
        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('goodsTypeName')" prop="goodsTypeName" label="分类" />
        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('goodsBrandName')" prop="goodsBrandName" label="商品品牌" />
        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('goodsTagName')" prop="goodsTagName" label="商品类型" />
        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('boxUnitCount')" prop="boxUnitCount" label="箱装量" />
        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('firstUnitName')" prop="firstUnitName" label="单位" width="100">
          <template slot-scope="scope">
            <span v-if="!scope.row.isSelected">{{ scope.row.firstUnitName }}{{ scope.row.firstUnitName }}</span>
            <zSelect v-if="scope.row.isSelected" :value.sync="scope.row.firstUnitId" :label="scope.row.firstUnitName" url="api/dropDown/basUnitList">
            </zSelect>
          </template>
        </el-table-column>
        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('boxCount')" prop="boxCount" label="箱数" />
        <!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('boxCount')" prop="boxCount" label="零数" >-->
        <!--        </el-table-column>-->
        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('boxUnitId')" prop="boxUnitId" label="辅数量" width="300">
          <template slot-scope="scope">
            <span v-if="!scope.row.isSelected">{{ scope.row.boxNum }}{{ scope.row.boxUnitName }}</span>
            <el-input v-if="scope.row.isSelected"
                      @input.native="crud.inuptCount(scope, 'boxNum')"
                      v-model="scope.row.boxNum"
                      style="width: 45%!important;">
              <template slot="append" >{{scope.row.boxUnitName}}</template>
            </el-input>
            <span v-if="!scope.row.isSelected">{{ scope.row.mainNum }}{{ scope.row.mainUnitName }}</span>
            <el-input v-if="scope.row.isSelected"
                      @input.native="crud.inuptCount(scope, 'mainNum')"
                      v-model="scope.row.mainNum"
                      style="width: 45%!important;">
              <template slot="append" >{{scope.row.mainUnitName}}</template>
            </el-input>
          </template>
        </el-table-column>
        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('goodsCount')" prop="goodsCount" label="数量" >
          <template slot-scope="scope">
            <span v-if="!scope.row.isSelected">{{ scope.row.goodsCount }}</span>
            <el-input v-if="scope.row.isSelected"
                      @input.native="crud.inuptCount(scope, 'goodsCount')"
                      oninput="value=value.replace(/[^\d^\.]/g,'')"
                      maxlength="12"
                      v-model.lazy="scope.row.goodsCount"
                      style="width: 100%"/>
          </template>
        </el-table-column>
        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('taxPrice')" prop="taxPrice" label="采购价" >
          <template slot-scope="scope">
            <span v-if="!scope.row.isSelected">{{ scope.row.taxPrice }}</span>
            <el-input v-if="scope.row.isSelected"
                      @input.native="crud.inuptCount(scope, 'taxPrice')"
                      oninput="value=value.replace(/[^\d^\.]/g,'')"
                      maxlength="12"
                      v-model.lazy="scope.row.taxPrice"
                      style="width: 100%"/>
          </template>
        </el-table-column>
        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('taxBoxPrice')" prop="taxBoxPrice" label="采购箱价" >
          <template slot-scope="scope">
            <span >{{ scope.row.taxBoxPrice }}</span>
            <!--            <el-input v-if="scope.row.isSelected"-->
            <!--                      @input.native="crud.inuptCount(scope, 'taxBoxPrice')"-->
            <!--                      oninput="value=value.replace(/[^\d^\.]/g,'')"-->
            <!--                      maxlength="12"-->
            <!--                      v-model.lazy="scope.row.noTaxPrice"-->
            <!--                      style="width: 100%"/>-->
          </template>
        </el-table-column>
        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('taxAmount')" prop="taxAmount" label="含税金额" >
          <!--          <template slot-scope="scope">-->
          <!--            <span v-if="!scope.row.isSelected">{{ scope.row.taxAmount }}</span>-->
          <!--            <el-input v-if="scope.row.isSelected"-->
          <!--                      oninput="value=value.replace(/[^\d^\.]/g,'')"-->
          <!--                      maxlength="12"-->
          <!--                      v-model.lazy="scope.row.taxAmount"-->
          <!--                      style="width: 100%"/>-->
          <!--          </template>-->
        </el-table-column>
        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('noTaxAmount')" prop="noTaxAmount" label="未税金额" >
          <!--          <template slot-scope="scope">-->
          <!--            <span v-if="!scope.row.isSelected">{{ scope.row.noTaxAmount }}</span>-->
          <!--            <el-input v-if="scope.row.isSelected"-->
          <!--                      oninput="value=value.replace(/[^\d^\.]/g,'')"-->
          <!--                      maxlength="12"-->
          <!--                      v-model.lazy="scope.row.noTaxAmount"-->
          <!--                      style="width: 100%"/>-->
          <!--          </template>-->
        </el-table-column>
        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('taxRate ')" prop="tax" label="税率" >
          <template slot-scope="scope">
            <span>{{ scope.row.taxRate }}%</span>
          </template>
        </el-table-column>
        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('tax')" prop="tax" label="税额" />
        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('costNoTaxAmount')" prop="costNoTaxAmount" label="未税成本金额" />
        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('costNoTaxPrice')" prop="costNoTaxPrice" label="未税成本单价" />
        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('costTaxAmount')" prop="costTaxAmount" label="含税成本金额" />
        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('costTaxPrice')" prop="costTaxPrice" label="含税成本单价" />



        <!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('taxName')" prop="taxName" label="税额" />-->
        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('remark')" prop="remark" label="备注"  width="200">
          <template slot-scope="scope">
            <span v-if="!scope.row.isSelected">{{ scope.row.remark }}</span>
            <el-input v-if="scope.row.isSelected"
                      type="textarea"
                      :rows="2"
                      v-model.lazy="scope.row.remark"
                      style="width: 100%"/>
          </template>
        </el-table-column>
        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('outStorehouseName')" prop="outStorehouseName" label="出库库位" />
        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('inStorehouseName')" prop="inStorehouseName" label="入库库位" />
        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('outProducedDate')" prop="outProducedDate" label="出库生产日期" >
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.outProducedDate) }}</span>
          </template>
        </el-table-column>
        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('outDeadlineDate')" prop="outDeadlineDate" label="出库截止日期" >
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.outDeadlineDate) }}</span>
          </template>
        </el-table-column>
        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('inProducedDate')" prop="inProducedDate" label="入库生产日期" >
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.inProducedDate) }}</span>
          </template>
        </el-table-column>
        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('inDeadlineDate')" prop="inDeadlineDate" label="出库生产日期" >
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.inDeadlineDate) }}</span>
          </template>
        </el-table-column>
        <!--        v-permission="['admin','buyProtocolDetail:edit','buyProtocolDetail:del']"-->
        <el-table-column :render-header="crud.renderHeader"  label="操作" fixed="right" width="150px" align="center">
          <template slot-scope="scope">
            <!--              <el-button-->
            <!--                type="primary"-->
            <!--                icon="el-icon-plus"-->
            <!--                circle-->
            <!--                v-if="(crud.data.length-1)==scope.$index"-->
            <!--                :disabled="crud.order.orderStatus==='PASS'"-->
            <!--                @click="crud.addRow(scope.$index)"></el-button>-->
            <!--              v-if="crud.data.length!==1"-->
            <el-button
              slot="reference" class="el-icon-delete opration_icon_btn"
              :disabled="crud.order.orderStatus==='PASS'"
              style="border: none;width: auto;height: auto"
              @click="delAddRow(scope.$index)"></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <!--      <pagination />-->
      <!--批量新增弹窗-->
      <el-dialog :close-on-click-modal="false" title="商品新增"
                 :visible.sync="showAddBatchDialog" append-to-body width="100vw">
        <add-batch v-if="showAddBatchDialog" :showAddBatchDialog.sync="showAddBatchDialog" :list="detailList"
                   :params="{customerId:crud.order.customerId,type:'STOCK',}"
                   @change="afterChangeGoods"></add-batch>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import crudWareAllotDetail from '@/api/erp/wareAllot'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import jtgSelectPlus from '@/components/select/JtgSelectPlus'
import { getCompany } from '@/api/system/company'
import {Notification} from "element-ui";
import addBatch from '@/components/addBatch/addBatch'
import crudWareAllot from '@/api/erp/wareAllot'
import jPrintConfig from '@/components/jPrintConfig/jPrintConfig'
// crud交由presenter持有
const defaultCrud = CRUD({ title: '调拨单明细',
  params() {
    const href = location.href.split('/')
    return {
      id: href[href.length - 1] == 'add' ? 0 : href[href.length - 1],  page: 0, size: 999,
    }
  }, optShow: {
    add: false,
    edit: false,
    del: true,
    download: false,
    leadingIn: false,
    enable: false,
    disable: false,
    pass: true,
    reject: true
  },
  url: 'api/wareAllot/detail', sort:'t.seq,asc',name:'wareAllotDetail', crudMethod: { ...crudWareAllotDetail }})
const defaultForm = { id: null, orderId: null, goodsId: null, goodsCode: null, goodsName: null, barcode: null, boxBarcode: null, helpSign: null, model: null, goodsBrandId: null, goodsBrandCode: null, goodsBrandName: null, goodsTypeId: null, goodsTypeCode: null, goodsTypeName: null, goodsTagId: null, goodsTagCode: null, goodsTagName: null, taxId: null, taxCode: null, taxName: null, taxRate: null, firstUnitId: null, firstUnitCode: null, firstUnitName: null, firstUnitCount: null, effectGoodsCount: null, cutOffGoodsCount: null, taxPrice: null, noTaxPrice: null, taxBoxPrice: null, noTaxBoxPrice: null, seq: null, remark: null, createUserId: null, createUserCode: null, createUserName: null, createTime: null, updateUserId: null, updateUserCode: null, updateUserName: null, updateTime: null }
export default {
  name: 'BuyProtocolDetail',
  components: { pagination, crudOperation, rrOperation, udOperation, jtgSelectPlus, addBatch, jPrintConfig},
  mixins: [presenter(defaultCrud), header(), form(defaultForm), crud()],
  dicts: ['common_order_status','t_ware_allot_type','t_ware_allot_source_type'],

  data() {
    return {
      id: null,
      permission: {
        add: ['admin', 'buyProtocolDetail:add'],
        edit: ['admin', 'buyProtocolDetail:edit'],
        del: ['admin', 'buyProtocolDetail:del'],
        import: ['admin', 'buyProtocolDetail:import'],
        export: ['admin', 'buyProtocolDetail:export'],
        copy: ['admin', 'buyProtocolDetail:copy'],
        upload: ['admin', 'buyProtocolDetail:upload'],
        download: ['admin', 'buyProtocolDetail:download'],
      },
      rules: {
        outWarehouseId: [
          { required: true, message: '出库仓库不能为空', trigger: 'blur' }
        ],
        inWarehouseId: [
          { required: true, message: '入库仓库不能为空', trigger: 'blur' }
        ],
        deptId: [
          { required: true, message: '采购部门不能为空', trigger: 'blur' }
        ],
        acceptDate: [
          { required: true, message: '到货日期不能为空', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '采购单类型不能为空', trigger: 'blur' }
        ],
        buyChannel: [
          { required: true, message: '渠道类型不能为空', trigger: 'blur' }
        ],
        sourceType: [
          { required: true, message: '来源类型不能为空', trigger: 'blur' }
        ],
        customerId: [
          { required: true, message: '供应商不能为空', trigger: 'blur' }
        ],
        userId: [
          { required: true, message: '业务员不能为空', trigger: 'blur' }
        ],
        isAppend: [
          { required: true, message: '是否追加不能为空', trigger: 'blur' }
        ],
        isContact: [
          { required: true, message: '是否第三方采购不能为空', trigger: 'blur' }
        ],
      },
      addRowData:{
        isSelected: true,id: null, orderId: null, goodsId: null, goodsCode: null, goodsName: null, barcode: null, boxBarcode: null, helpSign: null, model: null, goodsBrandId: null, goodsBrandCode: null, goodsBrandName: null, goodsTypeId: null, goodsTypeCode: null, goodsTypeName: null, goodsTagId: null, goodsTagCode: null, goodsTagName: null, taxId: null, taxCode: null, taxName: null, taxRate: null, firstUnitId: null, firstUnitCode: null, firstUnitName: null, firstUnitCount: null, effectGoodsCount: null, cutOffGoodsCount: null, taxPrice: null, noTaxPrice: null, taxBoxPrice: null, noTaxBoxPrice: null, seq: null, remark: null, createUserId: null, createUserCode: null, createUserName: null, createTime: null, updateUserId: null, updateUserCode: null, updateUserName: null, updateTime: null
      },
      showAddBatchDialog: false,
      productList:[]

    }
  },
  updated() {
    this.$nextTick(() => {
      this.$refs.table.doLayout()
    })
  },
  watch: {
  },
  destroyed() {
    this.crud.setItemInfo("wareAllotDetail_add")
  },

  created(){
    if (this.$route.params.id == 'add') {
      if( this.crud.getItemInfo("wareAllotDetail_add")){
        return false
      }
      this.crud.order = {
        id: null,
        code: '',
        busDate:  this.getTime(),
        // createTime: this.getTime(),
        name: '',
        userId: '',
        deptId: null,
        type: 1,
        buyChannel: 1,
        acceptDate: null,
        isContact: null,
        isAppend: null,
        orderStatus: 'SAVE',
        index: '0',
        customerId:'',
        contactName:'',
        contactPhone:'',
        startDate: null,
        endDate: null,
        remark: ''
      }
      // this.crud.data.push(JSON.parse(JSON.stringify(this.addRowData)))
    }
  },
  beforeUpdate() {
    if (this.$route.params.id != 'add') {
      this.id = this.$route.params.id
      this.query.id = this.id
      this.crud.order.id = this.id
    }
  },
  methods: {
    // 反向调拨
    handleClickReverseAllot(id){
      if(this.$route.params.id == 'add'){
        this.$message({
          type: 'error',
          message: '请先保存!'
        });
        return false
      }
      let ids = []
      ids.push(id)
      let data ={ids:ids}
      crudWareAllot.reverseAllot(data).then(res => {
        this.$message({
          type: 'success',
          message: '反向调拨成功!'
        });
      }).catch((res)=>{
      })
    },
    getInfoOut(e){
      this.crud.order.outWarehouseId = e.id
      this.crud.order.outWarehouseName = e.name
    },
    getInfoIn(e){
      this.crud.order.inWarehouseId = e.id
      this.crud.order.inWarehouseName = e.name
    },
    // 反审出库
    handleClickRejectOut(id){
      if(this.$route.params.id == 'add'){
        this.$message({
          type: 'error',
          message: '请先保存!'
        });
        return false
      }
      let ids = []
      ids.push(id)
      let data ={ids:ids}
      crudWareAllot.rejectOut(data).then(res => {
        this.$message({
          type: 'success',
          message: '反审出库成功!'
        });
      }).catch((res)=>{
      })
    },
    // 审核出库
    handleClickPassOut(id){
      if(this.$route.params.id == 'add'){
        this.$message({
          type: 'error',
          message: '请先保存!'
        });
        return false
      }
      let ids = []
      ids.push(id)
      let data ={ids:ids}
      crudWareAllot.passOut(data).then(res => {
        this.$message({
          type: 'success',
          message: '审核出库成功!'
        });
      }).catch((res)=>{
      })
    },
    handleClickPassIn(id){
      if(this.$route.params.id == 'add'){
        this.$message({
          type: 'error',
          message: '请先保存!'
        });
        return false
      }
      let ids = []
        ids.push(id)
      let data ={ids:ids}
      crudWareAllot.passIn(data).then(res => {
        this.$message({
          type: 'success',
          message: '审核入库成功!'
        });
      }).catch((res)=>{
      })
    },
    afterChangeGoods(goods) {
      this.showAddBatchDialog = false
      //去重，已经去重
      let arr = this.crud.data.map(detail=>detail.goodsId)
      let _goods = []
      let result = []
      goods.forEach(good => {
        // if(!arr.includes(goods.goodsId)){
        good.isSelected = true
        good.outWarehouseId = this.crud.order.outWarehouseId
        good.outWarehouseName = this.crud.order.outWarehouseName
        good.inWarehouseId = this.crud.order.inWarehouseId
        good.inWarehouseName = this.crud.order.inWarehouseName
        this.crud.data.push(good)
        // }
      })
      // this.calcuForm()
    },
    toAddList() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          //校验通过
          this.showAddBatchDialog = true
        } else {
          if (!this.crud.order.customerId) {
            this.$message.error("请先选择客户")
          }
          if (!this.crud.order.type) {
            this.$message.error("请先选择销售单类型")
          }
          if (!this.crud.order.buyChannel) {
            this.$message.error("请先选择采购渠道")
          }
        }
      })
    },
    getInfo(e){
      this.crud.order.warehouseId = e.warehouseId
      this.crud.order.deptId = e.deptId
      this.crud.order.deptId = e.deptId
      this.crud.order.userId = e.userId
    },
    delAddRow(i){
      if(this.$route.params.id !== 'add'){
        this.$confirm('此操作将直接删除此条产品记录, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.crud.delRow(i)
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      }else{
        this.crud.delRow(i)
      }
    },
    getValue(e,i){
      console.log('this.crud.data',this.crud.data )
      this.crud.data[i].productName = e
      // let temp = this.crud.data[2]
      // this.crud.data[3] = temp
      this.crud.data.map(item => {
        // item.existId = 0
        // item.existNum = 0
        if(item.existBox === null){
          item.existBox = 0
        }
        if(item.occupyBox === null){
          item.occupyBox = 0
        }
      })
    },
    getInput(e,name,i){
      console.log(',data.goodsName',e,name,i)
      if(this.crud.data){
        if(e){
          this.crud.data[i].goodsName = ''
          this.crud.data[i].goodsId= e
        }else{
          this.crud.data[i].goodsName = ''
          this.crud.data[i].goodsId= null
        }
      }
    },
    // 保存
    submit(){
      var oDate1 = new Date(this.crud.order.startDate);
      var oDate2 = new Date(this.crud.order.endDate);
      if(oDate1.getTime() > oDate2.getTime()){
        this.$message({
          message: '开始日期不能大于结束日期',
          type: 'warning'
        })
        this.crud.order.startDate = null
        this.crud.order.endDate = null
        return false
      }
      this.$refs['form'].validate(valid => {
        if (!valid) {
          return
        }
        const table_rules = [
          {name: '数量', value: 'goodsCount'},
          // {name: '采购价', value: 'taxPrice'},
          // {name: '未税单价', value: 'noTaxPrice'},
          // {name: '含税金额', value: 'taxAmount'},
          // {name: '未税金额', value: 'noTaxAmount'}
        ]
        const result = table_rules.some(({name, value}) => {
          const rules = this.$refs.table.data.some((item, index) => {
            if (!this.tableRules((index + 1), name, item[value])) return true
          })
          if (rules) return true
        })
        if (!result) this.save()
      })
    },
    tableRules(index, name, value) {
      if (!value) {
        Notification.error({title: '序号【' + index + '】' + name + '不能为空'})
        return false
      } else return true
    },
    getTime(date = new Date()){
      var y = date.getFullYear();
      var m = date.getMonth() + 1;
      m = m < 10 ? ('0' + m) : m;
      var d = date.getDate();
      d = d < 10 ? ('0' + d) : d;
      var h = date.getHours();
      h=h < 10 ? ('0' + h) : h;
      var minute = date.getMinutes();
      minute = minute < 10 ? ('0' + minute) : minute;
      var second=date.getSeconds();
      second=second < 10 ? ('0' + second) : second;
      // +' '+h+':'+minute+':'+second;
      return y + '-' + m + '-' + d+' '+h+':'+minute+':'+second
    },
    //保存
    save() {
      let that = this
      that.crud.loadingOpen()
      this.crud.data.forEach(item=>{
        item.outWarehouseId = this.crud.order.outWarehouseId
        item.inWarehouseId = this.crud.order.inWarehouseId
      })
      this.crud.order.detailList  = this.crud.data
      let params = this.crud.order

      crudWareAllotDetail.add(params).then(res => {
        if(res.success){
          this.crud.order  = res.data
          // this.crud.data = res.data.detailList
          let id=res.data.id
          if(this.$route.params.id == 'add'){
            this.$store.dispatch("tagsView/delView", this.$route);
            this.$router.push({params: {id}})
            this.crud.cleanItemInfo('wareAllotDetail_add')
          }
          this.$message({
            message: '保存成功',
            type: 'success'
          })
          that.crud.loadingClose()
        }else{
          that.crud.loadingClose()
          this.$message({
            message: res.msg,
            type: 'warning'
          })
        }

      }).catch((res)=>{
        that.crud.loadingClose()
      })
    },
    // 新增
    toAdd(){

      // if(!this.crud.order.customerId){
      //   this.$message({
      //     message: '请先选择供应商',
      //     type: 'error'
      //   })
      //   return false
      // }
      if(!this.crud.order.outWarehouseId){
        this.$message({
          message: '请先选择出库仓库',
          type: 'error'
        })
        return false
      }
      if(!this.crud.order.inWarehouseId){
        this.$message({
          message: '请先选择入库仓库',
          type: 'error'
        })
        return false
      }
      this.crud.data.push({
        isSelected: true,id: null, outWarehouseId:this.crud.order.outWarehouseId,outWarehouseName:this.crud.order.outWarehouseName, inWarehouseId:this.crud.order.inWarehouseId, inWarehouseName:this.crud.order.inWarehouseName,  orderId: null, goodsId: null, goodsCode: null, goodsName: null, barcode: null, boxBarcode: null, helpSign: null, model: null, goodsBrandId: null, goodsBrandCode: null, goodsBrandName: null, goodsTypeId: null, goodsTypeCode: null, goodsTypeName: null, goodsTagId: null, goodsTagCode: null, goodsTagName: null, taxId: null, taxCode: null, taxName: null, taxRate: null, firstUnitId: null, firstUnitCode: null, firstUnitName: null, firstUnitCount: null, effectGoodsCount: null, cutOffGoodsCount: null, taxPrice: null, noTaxPrice: null, taxBoxPrice: null, noTaxBoxPrice: null, seq: null, remark: null, createUserId: null, createUserCode: null, createUserName: null, createTime: null, updateUserId: null, updateUserCode: null, updateUserName: null, updateTime: null
      })
    },
    //修改
    toDetail(){
    },
    // 获取数据前设置好接口地址
    [CRUD.HOOK.beforeRefresh]() {
      return true
    }, // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form) {
    },

  }
}
</script>

<style scoped>
.table-img {
  display: inline-block;
  text-align: center;
  background: #ccc;
  color: #fff;
  white-space: nowrap;
  position: relative;
  overflow: hidden;
  vertical-align: middle;
  width: 32px;
  height: 32px;
  line-height: 32px;
}
</style>

